import 'package:flutter/material.dart';

// 平滑加载文本动画
class SmoothLoadingTextAnimation extends StatefulWidget {
  final String text;
  final TextStyle? style;
  final Duration speed;
  final int maxDots;

  const SmoothLoadingTextAnimation({
    super.key,
    required this.text,
    this.style,
    this.speed = const Duration(milliseconds: 500),
    this.maxDots = 3,
  });

  @override
  _SmoothLoadingTextAnimationState createState() =>
      _SmoothLoadingTextAnimationState();
}

class _SmoothLoadingTextAnimationState extends State<SmoothLoadingTextAnimation>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _fadeAnimation;
  int _dotCount = 0;
  int _nextDotCount = 1;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: widget.speed,
    )..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          setState(() {
            _dotCount = _nextDotCount;
            _nextDotCount = (_nextDotCount + 1) % (widget.maxDots + 1);
          });
          _controller.reset();
          _controller.forward();
        }
      });

    _fadeAnimation = Tween(begin: 0.0, end: 1.0).animate(_controller);
    _controller.forward();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        style: widget.style ?? DefaultTextStyle.of(context).style,
        children: [
          TextSpan(text: widget.text), // 固定文字部分
          if (_dotCount > 0) TextSpan(text: '.' * _dotCount), // 当前点号
          TextSpan(
            text: '.' * (_nextDotCount - _dotCount), // 新增的点号
            style: TextStyle(
              color: widget.style?.color?.withOpacity(_fadeAnimation.value) ??
                  DefaultTextStyle.of(context)
                      .style
                      .color
                      ?.withOpacity(_fadeAnimation.value),
            ),
          ),
        ],
      ),
    );
  }
}
